package com.guojian.jdbc.transaction;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.guojian.jdbc.DataSourceFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 事务管理器
 * 
 * @author guojian
 *
 */
@Slf4j
public class TransactionManager {

	private TransactionManager() {
	}

	public static boolean beginTransaction(String dataSourceName, Itransaction transaction) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(DataSourceFactory.getDataSource(dataSourceName));
		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
		try {
			transaction.execute();
			transactionManager.commit(status);
		} catch (Exception e) {
			log.error("=========执行失败,操作将回滚=====> {}", e.getMessage());
			transactionManager.rollback(status);
			return false;
		}
		return true;
	}

}
